package com.supos.progress.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {
	public static final String FORMAT_DATETIME_CHS = "yyyy年MM月dd日 HH:mm:ss";
	private static final String FORMAT_DATETIME_LONG = "yyyyMMddHHmmss";
	public static final String FORMAT_DATETIME = "yyyy-MM-dd HH:mm:ss";
	public static final String FORMAT_DATE = "yyyy-MM-dd";
	private static final String FORMAT_TIME = "HH:mm:ss";
	private static final String FORMAT_TIME_HOUR_MIN = "HH:mm";
	private static final String FORMAT_TIME_HHMMSS = "HHmmss";
	private static final String FORMAT_DATETIME_YYYYMMDD = "yyyyMMdd";
	private static final String FORMAT_DATETIME_4MIN = "yyyyMMddHHmm";

	public static long SECONDS_OF_ONE_MINUTE=60L;
	public static long SECONDS_OF_ONE_HOUR=60L*SECONDS_OF_ONE_MINUTE;
	public static long SECONDS_OF_ONE_DAY=24L*SECONDS_OF_ONE_HOUR;
	public static long SECONDS_OF_ONE_WEEK=7*24L*SECONDS_OF_ONE_HOUR;

    public static Calendar getMondayOfThisWeek(){
        //获取当前周一
        Calendar cal = Calendar.getInstance();
        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
        if(dayOfWeek>2){
            cal.add(Calendar.DAY_OF_MONTH,-(dayOfWeek-2));
        }else if(dayOfWeek==1){
            cal.add(Calendar.DAY_OF_MONTH,-6);
        }
        return cal;
    }

    public static Integer getYearMonth(Date date){

        if(date==null)
            return null;
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM");
        String dateStr=sdf.format(date);
        dateStr=dateStr.replaceFirst("-","");

        return Integer.valueOf(dateStr);

    }

    public static boolean withinDays(String start, String end){

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        //验证活动有效期
        Date now=new Date();
        boolean result=false;
        try {
            Date startDate=sdf.parse(start);
            Date endDate=sdf.parse(end);
            result =now.after(startDate)&& now.before(endDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }

	public final static String formatDate4HHMMSS(Date date) {
		if (date == null) {
			date = new Date();
		}
		return new SimpleDateFormat(FORMAT_TIME_HHMMSS).format(date);
	}

	public final static String formatDate4YYYYMMDD() {
		return format(FORMAT_DATETIME_YYYYMMDD);
	}

	/**
	 * 将当前时间转化为yyyy-MM-dd格式字符串
	 *
	 * @return
	 */
	public final static String formatDate() {
		return format(FORMAT_DATE);
	}

	/**
	 * 将当前时间转换为yyyy-MM-dd HH:mm:ss格式字符串
	 *
	 * @return
	 */
	public static String formatDateTime() {
		return format(FORMAT_DATETIME);
	}

	/**
	 * 将当前时间转换为yyyyMMddHHmmss格式字符串
	 *
	 * @return
	 */
	public final static String formatLongDateTime() {
		return format(FORMAT_DATETIME_LONG);
	}

	public final static String formatateTime4MIN() {
		return format(FORMAT_DATETIME_4MIN);
	}

	public final static String formatateTime4MIN(Date date) {
		return format(date, FORMAT_DATETIME_4MIN);
	}

	// public static void main(String[] args) {
	//
	// String c = formatateTime4MIN();
	//
	// //System.out.println(formatateTime4MIN(addDateMinu(parseLongDateTime4Min(c),
	// -1)));
	// }

	/**
	 * 将当前时间转换为HH:mm:ss格式字符串
	 *
	 * @return
	 */
	public final static String formatTime() {
		return format(FORMAT_TIME);
	}

	/**
	 * 获取指定格式的当前时间字符串
	 *
	 * @param strFormat
	 * @return
	 */
	public static String format(String strFormat) {
		return new SimpleDateFormat(strFormat).format(new Date());
	}

	public static String formatDate(String strFormat, Date date) {
		return new SimpleDateFormat(strFormat).format(date);
	}

	/**
	 * 将日期转化为yyyy-MM-dd格式字符串
	 *
	 * @param date
	 * @return
	 */
	public final static String formatDate(Date date) {
		return format(date, FORMAT_DATE);
	}

	/**
	 * 将日期转换为yyyy-MM-dd HH:mm:ss格式字符串
	 *
	 * @param date
	 * @return
	 */
	public static String formatDateTime(Date date) {
		return format(date, FORMAT_DATETIME);
	}

	/**
	 * 将日期时间转换为yyyyMMddHHmmss格式字符串
	 *
	 * @param date
	 * @return
	 */
	public final static String formatLongDateTime(Date date) {
		return format(date, FORMAT_DATETIME_LONG);
	}

	/**
	 * 将日期转换为HH:mm:ss格式字符串
	 *
	 * @param date
	 * @return
	 */
	public final static String formatTime(Date date) {
		return format(date, FORMAT_TIME);
	}

	/**
	 * 将日期转换为指定格式字符串
	 *
	 * @param date
	 * @param strFormat
	 * @return
	 */
	public final static String format(Date date, String strFormat) {
		return new SimpleDateFormat(strFormat).format(date);
	}

	/**
	 * 将strInputFormat格式的日期字符串strDate转换为strOutputFormat格式字符串
	 *
	 * @param strDate
	 * @param strInputFormat
	 * @param strOutputFormat
	 * @return
	 */
	public static String format(String strDate, String strInputFormat, String strOutputFormat) {

		if (strDate == null || strDate.trim().length() == 0) {
			return null;
		}

		try {
			SimpleDateFormat dbFormat = new SimpleDateFormat(strInputFormat);
			SimpleDateFormat displayFormat = new SimpleDateFormat(strOutputFormat);
			return displayFormat.format(dbFormat.parse(strDate));
		} catch (Throwable e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 将字符串转换为日期
	 *
	 * @param strDate
	 *            yyyy-MM-dd格式字符日期串
	 * @return
	 */
	public static Date parseDate(String strDate) {
		return parse(strDate, FORMAT_DATE);
	}

	public static Date parseDate(String strDate, String format) {
		return parse(strDate, format);
	}

	/**
	 * 将字符串转换为时间
	 *
	 * @param strDate
	 *            HH:mm:ss格式时间字符串
	 * @return
	 */
	public static Date parseTime(String strDate) {
		return parse(strDate, FORMAT_TIME);
	}

	public static Date parseTimeForHour(String str) {
		return parse(str, FORMAT_TIME_HOUR_MIN);
	}

	/**
	 * 将字符串转换为日期
	 *
	 * @param strDate
	 *            yyyy-MM-dd HH:mm:ss格式日期字符串
	 * @return
	 */
	public static Date parseDateTime(String strDate) {
		return parse(strDate, FORMAT_DATETIME);
	}

	/**
	 * 将字符串转换为日期时间
	 *
	 * @param strDate
	 *            yyyyMMddHHmmss格式日期字符串
	 * @return
	 */
	public static Date parseLongDateTime(String strDate) {
		return parse(strDate, FORMAT_DATETIME_LONG);
	}

	public static Date parseLongDateTime4Min(String strDate) {
		return parse(strDate, FORMAT_DATETIME_4MIN);
	}

	/**
	 * 将字符串转换为日期
	 *
	 * @param strDate
	 * @param strFormat
	 * @return
	 */
	public static Date parse(String strDate, String strFormat) {

		if (strDate == null || strDate.trim().length() == 0) {
			return null;
		}

		try {
			return new SimpleDateFormat(strFormat).parse(strDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 创建日期
	 *
	 * @param year
	 *            年
	 * @param month
	 *            月
	 * @param date
	 *            日
	 * @return
	 */
	public static Date buildDate(int year, int month, int date) {
		return buildDateTime(year, month, date, 0, 0, 0);
	}

	/**
	 * 创建时间
	 *
	 * @param year
	 *            年
	 * @param month
	 *            月
	 * @param date
	 *            日
	 *            时
	 * @param min
	 *            分
	 * @param sec
	 *            秒
	 * @return
	 */
	public static Date buildDateTime(int year, int month, int date, int hour, int min, int sec) {

		Calendar calendar = Calendar.getInstance();

		calendar.set(Calendar.YEAR, year);
		calendar.set(Calendar.MONTH, month);
		calendar.set(Calendar.DATE, date);
		calendar.set(Calendar.HOUR_OF_DAY, hour);
		calendar.set(Calendar.MINUTE, min);
		calendar.set(Calendar.SECOND, sec);
		calendar.set(Calendar.MILLISECOND, 0);

		return calendar.getTime();
	}

	public static Date buildDateTime(Date date, int hour, int min, int sec) {

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.HOUR_OF_DAY, hour);
		calendar.set(Calendar.MINUTE, min);
		calendar.set(Calendar.SECOND, sec);
		calendar.set(Calendar.MILLISECOND, 0);

		return calendar.getTime();
	}

	/**
	 * 获取时间date1与date2相差的秒数
	 *
	 * @param date1
	 *            起始时间
	 * @param date2
	 *            结束时间
	 * @return 返回相差的秒数
	 */
	public static int getOffsetSeconds(Date date1, Date date2) {
		int seconds = (int) ((date2.getTime() - date1.getTime()) / 1000);
		return seconds;
	}

	/**
	 * 获取时间date1与date2相差的天数
	 *
	 * @param date1
	 *            起始时间
	 * @param date2
	 *            结束时间
	 * @return 返回相差的天数
	 */
	public static int getOffsetDays(Date date1, Date date2){
		return (int) ((date2.getTime() - date1.getTime()) / (1000*60*60*24));
	}

	public static boolean compareDate(String date) {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date dt1 = df.parse(date);
			Date dt2 = df.parse(format(FORMAT_DATETIME));
			if (dt1.getTime() > dt2.getTime()) {
				return true;
			} else {
				return false;
			}
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		return false;
	}

	/**
	 * 获取时间date1与date2相差的分钟数
	 *
	 * @param date1
	 *            起始时间
	 * @param date2
	 *            结束时间
	 * @return 返回相差的分钟数
	 */
	public static int getOffsetMinutes(Date date1, Date date2) {
		return getOffsetSeconds(date1, date2) / 60;
	}

	public static Date addDateMinu(Date date, int minus) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.MINUTE, minus);
		date = cal.getTime();
		return date;
	}

	public static String getWeekOfDate(String datestr) {
		Date date = parseLongDateTime(datestr);
		String[] weekOfDays = { "0", "1", "2", "3", "4", "5", "6" };
		Calendar calendar = Calendar.getInstance();
		if (date != null) {
			calendar.setTime(date);
		}
		int w = calendar.get(Calendar.DAY_OF_WEEK) - 1;
		if (w < 0) {
			w = 0;
		}
		return weekOfDays[w];
	}

	public static int getDaysBetweenToDate(Date end, Date start) {
		Calendar calst = Calendar.getInstance();
		Calendar caled = Calendar.getInstance();

		calst.setTime(start);
		caled.setTime(end);
		// 设置时间为0时
		calst.set(Calendar.HOUR_OF_DAY, 0);
		calst.set(Calendar.MINUTE, 0);
		calst.set(Calendar.SECOND, 0);
		calst.set(Calendar.MILLISECOND, 0);
		caled.set(Calendar.HOUR_OF_DAY, 0);
		caled.set(Calendar.MINUTE, 0);
		caled.set(Calendar.SECOND, 0);
		caled.set(Calendar.MILLISECOND, 0);
		// 得到两个日期相差的天数
		int days = ((int) (caled.getTime().getTime() / 1000) - (int) (calst.getTime().getTime() / 1000)) / 3600 / 24;
		return days;
	}

	public static int compare_date(Date dt1, Date dt2) {
		try {
			if (dt1.getTime() > dt2.getTime()) {
				return 1;
			} else if (dt1.getTime() < dt2.getTime()) {
				return -1;
			} else {
				return 0;
			}
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		return 0;
	}

	public static Date nextDay(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DATE, 1);
		return cal.getTime();
	}

	public static Date beforeDay(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DATE, -1);
		return cal.getTime();
	}

	public static Date nextXMinute(Date date, int minute) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.MINUTE, minute);
		return cal.getTime();
	}

	public static Date beforeXDay(Date date, int day) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DATE, day);
		return cal.getTime();
	}

	public static Date addDateDay(Date date, int day) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DATE, day);
		// 设置时间为0时
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		date = cal.getTime();
		return date;
	}

	public static Date getLastFrd(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		if (Calendar.SATURDAY == cal.get(Calendar.DAY_OF_WEEK)) {
			cal.add(Calendar.DATE, -1);
		}
		if (Calendar.SUNDAY == cal.get(Calendar.DAY_OF_WEEK)) {
			cal.add(Calendar.DATE, -2);
		}
		return cal.getTime();
	}

    public static String getGroupName(Integer group) {

        String str = group+"";
        return str.substring(0,4)+"年"+str.substring(4,6)+"月";
    }

	public static Date getCleanDay(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);

		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		date = cal.getTime();
		return date;
	}

	public static Date getLastMomentDay(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);

		cal.set(Calendar.HOUR_OF_DAY, 23);
		cal.set(Calendar.MINUTE, 59);
		cal.set(Calendar.SECOND, 59);
		cal.set(Calendar.MILLISECOND, 999);
		date = cal.getTime();
		return date;
	}

	public static Integer getYearUpperLimitForTime(String year){
		if (!VerifyUtil.isInteger(year)) return null;

		Integer iYear = Integer.valueOf(year);
		switch (iYear){
			case 1990: return null;
			case 1980: return 1990;
			case 1970: return 1980;
			case 1960: return 1970;
			case 1950: return 1960;
			default: break;
		}

		return null;
	}

	public static Integer getYearLowerLimitForTime(String year){
		if (!VerifyUtil.isInteger(year)) return null;

		Integer iYear = Integer.valueOf(year);
		switch (iYear){
			case 1990: return 1990;
			case 1980: return 1980;
			case 1970: return 1970;
			case 1960: return 1960;
			case 1950: return null;
			default: break;
		}
		return null;
	}


	/**
	 * 是否是周末
	 * @param date
	 * @return true为是
	 */
	public static  boolean isWeekend(Date date){
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
		return dayOfWeek==1||dayOfWeek==7;
	}


    /**
     * 是否为周日
     * @param date
     * @return
     */
	public static boolean isSunday(Date date){
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
        return dayOfWeek==1;
    }

	/**
	 * 是否为周三
	 * @param date
	 * @return
	 */
	public static boolean isWednesday(Date date){
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
		return dayOfWeek==4;
	}

	/**
	 * 获取当前年份
	 * @param date
	 * @return
	 */
	public static int getYear(Date date){
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar.get(Calendar.YEAR);
	}

	/**
	 * 获取当前月份
	 * @param date
	 * @return
	 */
	public static int getMonth(Date date){
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar.get(Calendar.MONTH);
	}

	/**
	 * 获取当前日期
	 * @param date
	 * @return
	 */
	public static int getDayOfMonth(Date date){
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar.get(Calendar.DAY_OF_MONTH);
	}

	/**
	 * 增加月份
	 * @param date
	 * @param month
	 * @return
	 */
	public static Date addMonth(Date date, int month) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.MONTH, month);
		date = cal.getTime();
		return date;
	}

	/**
	 * 获取当年的第一天
	 * @return
	 */
	public static Date getCurrYearFirst(){
		Calendar currCal=Calendar.getInstance();
		int currentYear = currCal.get(Calendar.YEAR);
		return getYearFirst(currentYear);
	}

	/**
	 * 获取当年的最后一天
	 * @return
	 */
	public static Date getCurrYearLast(){
		Calendar currCal=Calendar.getInstance();
		int currentYear = currCal.get(Calendar.YEAR);
		return getYearLast(currentYear);
	}

	/**
	 * 获取某年第一天日期
	 * @param year 年份
	 * @return Date
	 */
	public static Date getYearFirst(int year){
		Calendar calendar = Calendar.getInstance();
		calendar.clear();
		calendar.set(Calendar.YEAR, year);
		Date currYearFirst = calendar.getTime();
		return currYearFirst;
	}

	/**
	 * 获取某年最后一天日期
	 * @param year 年份
	 * @return Date
	 */
	public static Date getYearLast(int year){
		Calendar calendar = Calendar.getInstance();
		calendar.clear();
		calendar.set(Calendar.YEAR, year);
		calendar.roll(Calendar.DAY_OF_YEAR, -1);
		Date currYearLast = calendar.getTime();

		return currYearLast;
	}

	/**
	 * 当月第一天日期
	 * @return
	 */
	public static String monthFirstDate(String dateStr){
		//获取前月的第一天
		Calendar   cal_1=Calendar.getInstance();//获取当前日期
		cal_1.setTime(DateUtil.parseDate(dateStr));
		cal_1.add(Calendar.MONTH, 0);
		cal_1.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
		return DateUtil.formatDateTime(cal_1.getTime());
	}

	/**
	 * 当月最后一天日期
	 * @return
	 */
	public static String monthLastDate(String dateStr){
		//获取前月的第一天
		Calendar cale = Calendar.getInstance();
		cale.setTime(DateUtil.parseDate(dateStr));
		cale.add(Calendar.MONTH, 1);
		cale.set(Calendar.DAY_OF_MONTH, 0);//设置为1号,当前日期既为本月第一天
		return DateUtil.formatDate(cale.getTime()) + " 23:59:59";
	}

	public static String dateDiff(String startTime, String endTime,
								  String format) {
		// 按照传入的格式生成一个simpledateformate对象
		SimpleDateFormat sd = new SimpleDateFormat(format);
		long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
		long nh = 1000 * 60 * 60;// 一小时的毫秒数
		long nm = 1000 * 60;// 一分钟的毫秒数
		long ns = 1000;// 一秒钟的毫秒数
		long diff;
		long day = 0;
		long hour = 0;
		long min = 0;
		long sec = 0;
		// 获得两个时间的毫秒时间差异
		try {
			diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
			day = diff / nd;// 计算差多少天
			hour = diff % nd / nh + day * 24;// 计算差多少小时
			min = diff % nd % nh / nm + day * 24 * 60;// 计算差多少分钟
			sec = diff % nd % nh % nm / ns;// 计算差多少秒
			// 输出结果
			if (day < 0)
				return "0天";
			return day + "天" + (hour - day * 24) + "小时"
					+ (min - day * 24 * 60) + "分钟" + sec + "秒";
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return "0";
	}

	public static long dateDiffTimestamp(String startTime, String endTime, String format) {
		SimpleDateFormat sd = new SimpleDateFormat(format);
		long diff = 0L;
		try {
			diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return diff/1000 < 0L? 0L:diff/1000;
	}

	public static void main(String[] args) {
		System.out.println(dateDiffTimestamp("2017-03-24", "2017-03-25", "yyyy-MM-dd"));
		System.out.println(dateDiff("2017-03-24", "2017-03-25", "yyyy-MM-dd"));
	}
}
